package com.uw.uwrpc.core.meta;

import com.alibaba.fastjson.JSON;
import com.uw.uwrpc.core.constant.UWConstant;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(of = {"scheme","ip","ip","contextPath"})
public class InstanceMeta {

    private String scheme;
    private String ip;
    private Integer port;
    private String contextPath;

    // 状态，0：下线，1：上线
    private Integer status = 1;

    private Map<String, String> parameters = new HashMap<>();

    public String instanceSign() {
        return String.join(UWConstant.SEPARATOR, Arrays.asList(ip, port.toString()));
    }

    public String toUrl() {
        return String.format("http://%s:%d/%s", ip, port, contextPath);
    }

    public String toMetas() {
        return JSON.toJSONString(this.getParameters());
    }


    public static InstanceMeta http(String host, Integer port) {
        return InstanceMeta.builder()
                .scheme("http")
                .ip(host)
                .port(port)
                .contextPath("uwrpc")
                .parameters(new HashMap<>())
                .build();
    }

}
